#-*- coding:utf-8 -*-
from CIMConnection.Client import *
from comm.loglib import *
from config import *

class perinfolist(list):
   """
   cmd,pid,vsz,rsz,%cpu
   """
   def __init__(self, out):
      list.__init__(self)
      lines = out.splitlines()[:-1]
      if lines:
         self._process(lines)
         
   def _process(self, lines):
      for line in lines:
         self.append(perinfo(line))
         
   def __str__(self):
      return '\n'.join(map(str,self))
         
         
class perinfo(object):
   """
   """
   def __init__(self, line):
      self.line = line
      attrs = line.split()
      self.pid, self.vsz, self.rsz, self.cpu = attrs[-4:]
      self.cmd = ' '.join(attrs[:-4])
      
   def __str__(self):
      return self.line

def collect_performance_info(client, filter=None):
   """
   ps -eo cmd,pid,vsz,rsz,%cpu | grep cims | grep -v grep
   """
   filter = filter or config.get('CIM Agent', 'pidfilter')
   cmd = "ps -eo cmd,pid,vsz,rsz,%%cpu | grep %s | grep -v grep" % filter
   return client.exec_cmd(cmd, perinfolist)


def collection_thread(interval=5, cont=2*60*60, handle=None):
   import time
   pause_logging()
   client = CIMClient()
   interval = int(interval)
   cont = int(cont)
   st = time.time()
   handle = handle or sysout
   while time.time() - st < cont:
      try:
         out = collect_performance_info(client)
         if not out:
            handle('Process not found!')
            continue
         if len(out) > 1:
            handle('More than one process found on system')
         handle(out[0].pid, out[0].vsz, out[0].rsz, out[0].cpu)
      except Exception, e:
         handle(str(e))
         client.close_connection()
         client = CIMClient()
      time.sleep(interval)
   

if __name__ == '__main__':
   collection_thread()